﻿using Shop.Model.DB;
using Shop.Model.FrontCategory;
using Shop.Model.FrontCategoryBind;
using Shop.Repository;
using WeDonekRpc.Helper;

namespace Shop.Collect.lmpl
{
    internal class FrontCategoryBindCollect : IFrontCategoryBindCollect
    {
        private readonly IFrontCategoryBindRepository _Repository;

        public FrontCategoryBindCollect (IFrontCategoryBindRepository repository)
        {
            this._Repository = repository;
        }
        public CategoryBindDto[] GetAll ()
        {
            return this._Repository.GetAll<CategoryBindDto>();
        }
        public void Clear (long[] categoryId)
        {
            long[] ids = this._Repository.Gets(a => categoryId.Contains(a.CategoryId), a => a.Id);
            if (ids.IsNull())
            {
                return;
            }
            this._Repository.Delete(ids);
        }
        public bool Set (DBFrontCategory front, long[] categoryId)
        {
            var datas = this._Repository.Gets(a => a.FrontCategoryId == front.Id, a => new
            {
                a.Id,
                a.CategoryId
            });
            if (datas.IsNull() && categoryId.IsNull())
            {
                return false;
            }
            else if (!datas.IsNull() && categoryId.IsNull())
            {
                this._Repository.Delete(datas.ConvertAll(a => a.Id));
                return true;
            }
            else if (datas.IsNull())
            {
                this._Repository.Add(new FrontBindAdd
                {
                    FrontId = front.Id,
                    CategoryId = categoryId,
                    Lvl = front.Lvl
                });
                return true;
            }
            else if (categoryId.IsEqual(datas, (a, b) => a == b.CategoryId))
            {
                return false;
            }
            else
            {
                this._Repository.Set(new FrontBindAdd
                {
                    CategoryId = categoryId,
                    FrontId = front.Id,
                    Lvl = front.Lvl
                }, datas.ConvertAll(a => a.Id));
                return true;
            }
        }

        public long GetFrontCategoryId (long[] categoryId)
        {
            return this._Repository.Get(a => categoryId.Contains(a.CategoryId), a => a.FrontCategoryId, "Lvl desc");
        }
    }
}
